/**
 * @description works controller
 */

const {
  findWorkList,
  updateWorks,
  getWorksCount,
  getCreatedCountMonthly,
  getPublishedCountMonthly
} = require('../service/works')
const { SuccessRes, ErrorRes } = require('../res-model/index')
const { updateFailInfo, pageIndexFailInfo } = require('../res-model/failInfo')
const { publishWorkClearCache } = require('../cache/works/publish')
const { parseNumberArr } = require('../utils/util')

/**
 * 查询作品列表
 * @param {string} keyword 搜索关键字
 */
async function getWorksList(keyword = '', pageIndex, pageSize) {
  if (pageIndex && parseInt(pageIndex) <= 0) {
    return new ErrorRes(pageIndexFailInfo)
  }

  // 查询条件
  let whereOpt = {}
  if (keyword) {
    const keywordOpt = { $regex: keyword, $options: 'i' } //$regex 正则，用于实现模糊查询  $options: 'i' 忽略大小写

    whereOpt = {
      // 所有查询条件，$or 拼接
      $or: [{ title: keywordOpt }, { author: keywordOpt }]
    }

    const idKeyword = parseInt(keyword)
    // Number.isFinite()函数检查变量是否为数字，还检查其是否为有限值
    if (Number.isFinite(idKeyword)) {
      whereOpt.$or.push({ id: idKeyword })
    }
  }

  const pageOpt = {
    ...(pageIndex && { pageIndex: parseInt(pageIndex) - 1 }),
    ...(pageSize && { pageSize: parseInt(pageSize) })
  }

  const res = await findWorkList(whereOpt, pageOpt)

  return new SuccessRes(res)
}

/**
 * 强制下线
 * @param {string}} ids 如 '1' '1,2,3'
 */
async function forceOffline(ids = '') {
  // 将 ids 字符串变为数组
  const idsArr = parseNumberArr(ids)
  if (idsArr.length === 0) return new ErrorRes(updateFailInfo)

  // 更新
  const result = await updateWorks(
    { $set: { status: 3 } }, // 3 即为强制下线
    {
      id: { $in: idsArr },
      status: 2 // 只有发布状态，才能强制下线
    }
  )
  if (!result) return new ErrorRes(updateFailInfo)

  // 清空 h5 的缓存
  idsArr.forEach(id => publishWorkClearCache(id))

  return new SuccessRes()
}

/**
 * 恢复
 * @param {string}} ids 如 '1' '1,2,3'
 */
async function undoForceOffline(ids = '') {
  // 将 ids 字符串变为数组
  const idsArr = parseNumberArr(ids)
  if (idsArr.length === 0) return new ErrorRes(updateFailInfo)

  // 更新
  const result = await updateWorks(
    { $set: { status: 2 } }, // 2 即正常上线
    {
      id: { $in: idsArr },
      status: 3 // 只有强制下线状态，才能恢复为上线
    }
  )

  if (result) return new SuccessRes()
  return new ErrorRes(updateFailInfo)
}

/**
 * 获取创建和发布的总数
 */
async function getCount() {
  const created = await getWorksCount()
  const published = await getWorksCount({ status: 2 })
  return new SuccessRes({
    created,
    published
  })
}

/**
 * 获取每月创建和发布的总数
 */
async function getMonthlyCount() {
  // 一年的时间范围
  const d = new Date() // new Date() 生成是世界标准时区；和我们相差8个小时
  const startTime = new Date(d.getTime() - 365 * 24 * 60 * 60 * 1000) // 一年之前
  const endTime = d

  // 获取每月创建的数量
  const createdResult = await getCreatedCountMonthly(startTime, endTime)

  // 获取每月发布的数量
  const publishedResult = await getPublishedCountMonthly(startTime, endTime)

  // console.log('createdResult', createdResult)
  // console.log('publishedResult', publishedResult)

  // 格式化数据
  const resDataObj = {}
  createdResult.forEach(item => {
    const { _id, count = 0 } = item || {}
    if (!_id) return
    if (resDataObj[_id] == null) resDataObj[_id] = {}

    const data = resDataObj[_id]
    data.created = count
    if (data.published == null) data.published = 0
  })
  publishedResult.forEach(item => {
    const { _id, count = 0 } = item || {}
    if (!_id) return
    if (resDataObj[_id] == null) resDataObj[_id] = {}

    const data = resDataObj[_id]
    data.published = count
    if (data.created == null) data.created = 0
  })
  const _idKeys = Object.keys(resDataObj)
  const resData = _idKeys.map(_id => {
    return {
      month: _id,
      data: resDataObj[_id]
    }
  })

  return new SuccessRes(resData)
}

module.exports = {
  getWorksList,
  forceOffline,
  undoForceOffline,
  getCount,
  getMonthlyCount
}
